package com.demo2do.fms.queue.adapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.demo2do.core.utils.JsonUtils;
import com.demo2do.fms.entity.vam.MessageType;
import com.demo2do.fms.entity.vam.VamMessage;
import com.demo2do.fms.queue.entity.VehicleDelete;
import com.demo2do.fms.queue.service.VamMessageService;
import com.demo2do.fms.queue.service.VehicleService;
import com.rabbitmq.client.Channel;

/**
 *
 * @author Ark
 *
 */
@Component("vehicleDeleteAdapter")
public class VehicleDeleteAdapter extends MessageListenerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(VehicleDeleteAdapter.class);
    
    @Autowired
    private VehicleService vehicleService;
    
    @Autowired
    private VamMessageService vamMessageService;
    
    /* (non-Javadoc)
     * @see org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter#onMessage(org.springframework.amqp.core.Message, com.rabbitmq.client.Channel)
     */
    public void onMessage(Message message, Channel channel) throws Exception {
        
        String messageBody = null;
        
        try {
            
            messageBody = new String(message.getBody(), "UTF-8");
            logger.info("#onMessage() - messageBody=[{}]", messageBody);
            VehicleDelete vehicleDelete = JsonUtils.parse(messageBody, VehicleDelete.class);
            
            vehicleService.delete(vehicleDelete);
            
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            
        } catch (Exception e) {
            
            VamMessage vamMessage = new VamMessage(MessageType.VEHICLE_DELETE, messageBody, e.getMessage());
            vamMessageService.save(vamMessage);
            
            logger.error("onMessage() - occur exception is [{}]", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            
        }
        
    }
    
}
